#!/bin/bash
#
# Start a Marmot seed node (node 1)
#
# Usage: ./start-seed.sh
#
# This starts node 1 as the seed node. Other nodes can join using:
#   ./join-cluster.sh 2 localhost:8081
#   ./join-cluster.sh 3 localhost:8081

set -e

NODE_ID=1
MYSQL_PORT=3307
GRPC_PORT=8081

DATA_DIR="/tmp/marmot-node-${NODE_ID}"
CONFIG_FILE="/tmp/marmot-node-${NODE_ID}.toml"

echo "=== Marmot Seed Node ==="
echo "Node ID:     ${NODE_ID}"
echo "MySQL Port:  ${MYSQL_PORT}"
echo "gRPC Port:   ${GRPC_PORT}"
echo "Data Dir:    ${DATA_DIR}"
echo ""

# Kill any existing marmot processes on our ports
echo "Stopping any existing processes on ports ${MYSQL_PORT}, ${GRPC_PORT}..."
lsof -ti:${MYSQL_PORT} -ti:${GRPC_PORT} 2>/dev/null | xargs kill 2>/dev/null || true
sleep 1

# Clean up previous data
echo "Cleaning up previous data directory..."
rm -rf "${DATA_DIR}"

mkdir -p "${DATA_DIR}"

# Generate config file
cat > "${CONFIG_FILE}" << EOF
# Marmot Seed Node Configuration
# Auto-generated by start-seed.sh

node_id = ${NODE_ID}
data_dir = "${DATA_DIR}"

[cluster]
grpc_bind_address = "0.0.0.0"
grpc_port = ${GRPC_PORT}
grpc_advertise_address = "localhost:${GRPC_PORT}"
seed_nodes = []  # Empty - this is the seed node
gossip_interval_ms = 1000
gossip_fanout = 3
suspect_timeout_ms = 5000
dead_timeout_ms = 15000

[mysql]
enabled = true
bind_address = "0.0.0.0"
port = ${MYSQL_PORT}

[replication]
default_write_consistency = "QUORUM"  # Replicate to majority
default_read_consistency = "LOCAL_ONE"
write_timeout_ms = 5000
read_timeout_ms = 2000

# Anti-Entropy: Background healing for eventual consistency
enable_anti_entropy = true
anti_entropy_interval_seconds = 60      # Run anti-entropy every 60 seconds
delta_sync_threshold_transactions = 10000  # Use delta sync if lag < 10K txns
delta_sync_threshold_seconds = 3600     # Use snapshot if lag > 1 hour

# Garbage Collection: Reclaim disk space by deleting old transaction records
gc_min_retention_hours = 2   # Minimum 2 hours (must be >= delta threshold)
gc_max_retention_hours = 24  # Force delete after 24 hours

[mvcc]
gc_interval_seconds = 30         # Run GC every 30 seconds
gc_retention_hours = 1           # Minimum age for GC consideration
heartbeat_timeout_seconds = 10   # Timeout for transaction heartbeats
version_retention_count = 10     # Keep last 10 MVCC versions per row
conflict_window_seconds = 10     # Window for LWW conflict resolution

[logging]
verbose = true
format = "console"

[prometheus]
enabled = true
EOF

# Find or build marmot-v2 binary
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

if [ -f "$REPO_ROOT/marmot-v2" ]; then
    MARMOT_BIN="$REPO_ROOT/marmot-v2"
else
    echo "Building marmot-v2..."
    cd "$REPO_ROOT"
    go build -tags sqlite_preupdate_hook -o marmot-v2 .
    MARMOT_BIN="$REPO_ROOT/marmot-v2"
    echo "✓ Build complete"
fi

echo "Starting seed node..."
echo "Connect with: mysql -h localhost -P ${MYSQL_PORT} -u root"
echo ""
echo "To add more nodes:"
echo "  ./join-cluster.sh 2 localhost:${GRPC_PORT}"
echo "  ./join-cluster.sh 3 localhost:${GRPC_PORT}"
echo ""

exec ${MARMOT_BIN} --config "${CONFIG_FILE}"
